import { Component, Injector, ViewChild } from '@angular/core';
import { AppComponentBase } from '@shared/common/app-component-base';
import { ActivatedRoute, Params, Router } from '@angular/router';
import { appModuleAnimation } from '@shared/animations/routerTransition';
import { ConfigFileDto, EntityDtoOfGuid, IEntityDtoOfGuid, MenuCleanServiceProxy, ModuleServiceProxy, SetStatusInput } from '@shared/service-proxies/service-proxies';
import { LazyLoadEvent } from 'primeng/api';
import { Paginator } from 'primeng/paginator';
import { Table } from 'primeng/table';
import { finalize } from 'rxjs/operators';
import { IJsonEditorModalCallbackData, JsonEditorModalComponent } from '@app/shared/common/json-editor/json-editor-modal.component';
import { CreateOrEditModuleModalComponent } from './create-or-edit-module-modal.component';


@Component({
    templateUrl: './backendPage.component.html',
    animations: [appModuleAnimation()]
})
export class BackendPageComponent extends AppComponentBase {

    @ViewChild('dataTable', { static: true }) dataTable: Table;
    @ViewChild('paginator', { static: true }) paginator: Paginator;
    @ViewChild('jsonEditorModal', { static: true }) jsonEditorModal: JsonEditorModalComponent;
    @ViewChild('createOrEditModuleModal', { static: true }) createOrEditModuleModal: CreateOrEditModuleModalComponent;

    
    filterText = '';
    selectedDatas: IEntityDtoOfGuid[];
    loading = false;

    constructor(
        injector: Injector,
        private _router: Router,
        private _moduleService: ModuleServiceProxy,
        private _menuCleanService: MenuCleanServiceProxy) {
        super(injector);
    }

    ngOnInit() {
        this.getListData(null);
    }

    getListData(event?: LazyLoadEvent) {
        if (this.primengTableHelper.shouldResetPaging(event)) {
            if (this.primengTableHelper.TryChangePage(this.paginator, 0)) {
                return;
            }
        }

        this.selectedDatas = [];

        this.primengTableHelper.showLoadingIndicator();
        this._moduleService.getPagedModules(
            this.filterText,
            this.primengTableHelper.getSorting(this.dataTable),
            this.primengTableHelper.getMaxResultCount(this.paginator, event),
            this.primengTableHelper.getSkipCount(this.paginator, event)
        ).pipe(finalize(() => this.primengTableHelper.hideLoadingIndicator())).subscribe(result => {
            this.primengTableHelper.totalRecordsCount = result.totalCount;
            this.primengTableHelper.records = result.items;
            this.primengTableHelper.hideLoadingIndicator();
        });
    }

    reloadPage() {
        if (this.primengTableHelper.TryChangePage(this.paginator, this.paginator.getPage())) {
            return;
        }

        this.getListData(null);
    }

    editModule(entry) {
        this.openCreateOrEdit(entry);
    };
    createNews() {
        this.openCreateOrEdit(null);
    }

    delete() {
        if (!this.selectedDatas) return;
        let ids = this.selectedDatas.map(item => item.id);
        if (ids.length == 0) return;
        this.message.confirm(this.l('DeleteWarningMessage'), this.l('AreYouSure'),
            (isConfirmed) => {
                if (!isConfirmed) return;
                this._moduleService.deleteList(ids)
                    .subscribe(() => {
                        this.selectedDatas = [];
                        this.reloadPage();
                        this.notify.success(this.l('SuccessfullyDeleted'));
                    });
            })
    }

    deleteSingle(entity) {
        this.message.confirm(this.l('DeleteWarningMessage'), this.l('AreYouSure'),
            (isConfirmed) => {
                if (!isConfirmed) return;
                this._moduleService.delete(entity.id)
                    .subscribe(() => {
                        this.selectedDatas = [];
                        this.reloadPage();
                        this.notify.success(this.l('SuccessfullyDeleted'));
                    });
            })
    }


    changeState(state: boolean) {
        if (!this.selectedDatas) return;
        let ids = this.selectedDatas.map(item => item.id);

        if (ids.length > 0) {
            let msg: string;
            if (state) {
                msg = this.l('ReleaseWarningMessage');
            }
            else {
                msg = this.l('UndoReleaseWarningMessage');
            }
            this.message.confirm(msg, this.l('AreYouSure'),
                (isConfirmed) => {
                    if (!isConfirmed) return;

                    let input = new SetStatusInput();
                    input.idList = ids;
                    input.isActive = state;

                    this._moduleService.setStatus(input)
                        .subscribe(() => {
                            this.selectedDatas = [];
                            this.getListData(null);
                            if (state) {
                                this.notify.success(this.l('ReleaseSuccessfully'));
                            } else {
                                this.notify.success(this.l('CancelReleaseSuccessfully'));
                            }
                        });
                })
        }
    }

    openCreateOrEdit(entry) {
        if(entry){
            this.createOrEditModuleModal.show(entry.id, entry.displayName);
        }else{
            this.createOrEditModuleModal.show(undefined, '');
        }
    }

    resetMenusCache() {
        this.loading = true;
        this._menuCleanService.resetMenuCacheByHost()
            .pipe(finalize(() => this.loading = false))
            .subscribe(result => {
                this.notify.success(this.l('CacheSuccessfullyCleared'));
            });
    }

    goFrontendPage(entity) {
        this._router.navigate(['app/admin/frontendPage', {
            backEndModuleId : entity.id
        }]);
    }

    copyModule (entity) {
        this.loading = true;
        this._moduleService.copyNewOne(new EntityDtoOfGuid({ id: entity.id }))
        .pipe(finalize(() => this.loading = false))
        .subscribe(result => {
            this.notify.success(this.l('CopySuccessfully'));
            this.getListData(null);
        });
    }

    config() {
        this.loading = true;
        this._moduleService.getConfigFileContent()
        .pipe(finalize(() => this.loading = false))
        .subscribe(result => {
            let data: any ={};
            try{
                data = JSON.parse(result);
            }catch(e){
                console.log(e);
            }
            
            this.jsonEditorModal.configure({
                message: 'config',
                data: data,
                schema : this.configSchema
            });
            this.jsonEditorModal.show();
        });
    }
    readonly configSchema: any = {
        'type': 'object',
        'title': 'The Root Schema',
        'required': [
          'GuidValue',
          'LongValue'
        ],
        'properties': {
          'GuidValue': {
            'type': 'object'
          },
          'LongValue': {
            'type': 'object'
          }
        }
    };
      
    configSave(e:IJsonEditorModalCallbackData){
        this.loading = true;
        this._moduleService.updateOrCreateConfigFile(new ConfigFileDto({content: e.data}))
        .pipe(finalize(() => this.loading = false))
        .subscribe(result => {
            this.notify.success(this.l('SavedSuccessfully'));
        });
    }
}
